<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        span {

            display: block;
            position: absolute;
            width: 100px;
            height: 100px;
            left: 0;
            background-color: purple;
        }
        button{
            margin-left: 500px;
        }
    </style>
</head>

<body>
    <div></div>
    <span></span>
    <button>点击开炮</button>
    <script>
        var div = document.querySelector('div');
        var span = document.querySelector('span');
        var btn=document.querySelector('button');
        animate(div, 300);
        
        //obj目标元素，target目标位置
        function animate(obj, target) {
            //防止吧、鹔加快先清除以前的定时器
            clearInterval(obj.time);
            //给不同的元素指定不同的定时器
            obj.time = setInterval(function () {
                if (obj.offsetLeft >= target) {
                    clearInterval(obj.time);
                } else {
                    obj.style.left = obj.offsetLeft + 1 + 'px';
                }
            }, 1)
        };
        btn.addEventListener('click',function(){
            //bug:当不断点击按钮元素速度会越来越快
            //解决方案：元素只有一个定时器执行
            animate(span, 200);
        })
        console.dir(div);
    </script>
</body>

</html>